# pip install cos-python-sdk-v5
import traceback
from settings import *
from qcloud_cos import CosConfig, CosS3Client

secret_id = COS_SECRET_ID     # 用户的 SecretId，建议使用子账号密钥，授权遵循最小权限指引，降低使用风险。子账号密钥获取可参见 https://cloud.tencent.com/document/product/598/37140
secret_key = COS_SECRET_KEY   # 用户的 SecretKey，建议使用子账号密钥，授权遵循最小权限指引，降低使用风险。子账号密钥获取可参见 https://cloud.tencent.com/document/product/598/37140
region = COS_REGION      # 替换为用户的 region，已创建桶归属的 region 可以在控制台查看，https://console.cloud.tencent.com/cos5/bucket
                           # COS 支持的所有 region 列表参见 https://cloud.tencent.com/document/product/436/6224
scheme = COS_SCHEMA           # 指定使用 http/https 协议来访问 COS，默认为 https，可不填
default_bucket = COS_DEFAULT_BUCKET

config = CosConfig(Region=region, SecretId=secret_id, SecretKey=secret_key, Scheme=scheme)
client = CosS3Client(config)


def go_upload_file(file, bucket=default_bucket, path_name='', **kwargs):
    """
    上传文件
    :param file:
    :param bucket:
    :param path_name:
    :param kwargs:
    :return:
    """
    try:
        client.put_object(
            Bucket=bucket,
            Body=file,
            Key=path_name,
            **kwargs
        )
        return 1
    except Exception as e:
        print(traceback.format_exc())
    return 0


def go_delete_file(bucket=default_bucket, path_name=''):
    """
    删除文件
    :param bucket:
    :param path_name:
    :return:
    """
    try:
        client.delete_object(Bucket=bucket, Key=path_name)
        return 1
    except Exception as e:
        print(traceback.format_exc())
        return 0


def get_file_url(bucket=default_bucket, path_name=''):
    """
    获取文件路径
    :param bucket:
    :param path_name:
    :return:
    """
    try:
        url = client.get_object_url(Bucket=bucket, Key=path_name)
        return url
    except Exception as e:
        print(e)
        return None


def get_file_object(bucket=default_bucket, path_name=''):
    """
    获取文件路径
    :param bucket:
    :param path_name:
    :return:
    """
    try:
        response = client.get_object(Bucket=bucket, Key=path_name)
        fp = response['Body'].get_raw_stream()
        return fp.read()
    except Exception as e:
        print(e)
        return None
